package com.xiyou.week05.binarySearch;

import java.util.Arrays;

/**
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 *
 * @ClassName：SearchRange
 * @Author：西柚
 * @Date：2022/1/27 11:53 上午
 * @Versiion：1.0
 */
public class SearchRange {

    public int[] searchRange(int[] nums, int target) {
        // 开始位置：第一个>=target的数
        // 结束位置：最后一个<=target的数
        int left = 0, right = nums.length;
        while (left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] >= target) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }

        int[] ans = new int[2];
        ans[0] = right;

        left = -1;
        right = nums.length - 1;
        while (left < right) {
            int mid = (left + right + 1) / 2;
            if (nums[mid] <= target) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        ans[1] = right;

        if (ans[0] > ans[1]) {
            return new int[]{-1, -1};
        }

        return ans;
    }

    public static void main(String[] args) {
//        int[] nums = new int[]{5, 7, 7, 8, 8, 10};
//        int target = 8;
        int[] nums = new int[]{2, 2};
        int target = 3;
        SearchRange search = new SearchRange();
        System.out.println(Arrays.toString(search.searchRange(nums, target)));
    }

}
